package com.xinyue.chat.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.EncoderException;
import io.netty.util.CharsetUtil;

public class EncodeHandler extends ChannelOutboundHandlerAdapter {
	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		if (msg instanceof ByteBuf) {
			ByteBuf byteBuf = (ByteBuf)msg;
			ctx.write(byteBuf);
			return;
		}
		ByteBuf buf = null;
		try {
			MessageResponse response = (MessageResponse) msg;
			buf = encode(ctx, response);
			if (buf.isReadable()) {
				ctx.write(buf, promise);
			} else {
				buf.release();
				ctx.write(Unpooled.EMPTY_BUFFER, promise);
			}
			buf = null;
		} catch (EncoderException e) {
			throw e;
		} catch (Throwable e) {
			throw new EncoderException(e);
		} finally {
			if (buf != null) {
				buf.release();
			}
		}
	}

	protected ByteBuf encode(ChannelHandlerContext ctx, MessageResponse response) throws Exception {

		int total = MessageHeader.HeaderLength; // 这是整个包头的字节长度
		byte[] body = null;
		if (response.getResponseBody() != null) {
			String json = response.getResponseBody().toJSONString();
			body = json.getBytes(CharsetUtil.UTF_8);
			total += body.length;
		}
		ByteBuf out = ctx.alloc().directBuffer(total);
		MessageHeader header = response.getHeader();
		out.writeInt(total);
		out.writeInt(header.getMessageId());
		out.writeInt(header.getSeqId());
		out.writeByte(header.getMessageType());

		out.writeLong(header.getClientSendTime());
		out.writeLong(System.currentTimeMillis());
		if (body != null) {
			out.writeBytes(body);
		}
		return out;
	}
}
